<template>
  <div class="grade-manage">
    <el-card class="action-card">
      <template #header>
        <div class="card-header">
          <span>成绩管理</span>
          <el-button type="primary" @click="handleExport">导出成绩</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="学生姓名">
          <el-input v-model="searchForm.studentName" placeholder="请输入学生姓名" clearable />
        </el-form-item>
        <el-form-item label="考试名称">
          <el-input v-model="searchForm.examTitle" placeholder="请输入考试名称" clearable />
        </el-form-item>
        <el-form-item label="考试时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="是否通过">
          <el-select v-model="searchForm.isPassed" placeholder="请选择" clearable>
            <el-option label="通过" :value="1" />
            <el-option label="未通过" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 成绩列表 -->
      <el-table :data="gradeList" border style="width: 100%">
        <el-table-column prop="studentName" label="学生姓名" min-width="100" />
        <el-table-column prop="studentId" label="学号" width="120" />
        <el-table-column prop="examName" label="考试名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="examTime" label="考试时间" width="180" />
        <el-table-column prop="score" label="总分" width="80">
          <template #default="{ row }">
            {{ row.score }}分
          </template>
        </el-table-column>
        <el-table-column prop="isPassed" label="是否通过" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isPassed ? 'success' : 'danger'">
              {{ row.isPassed ? '通过' : '未通过' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cheatingFlag" label="作弊标记" width="100">
          <template #default="{ row }">
            <el-tag :type="getCheatingTagType(row.cheatingFlag)">
              {{ getCheatingTagText(row.cheatingFlag) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleDetail(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 导出对话框 -->
    <el-dialog v-model="exportVisible" title="导出成绩数据" width="500px">
      <el-form label-width="100px">
        <el-form-item label="导出范围">
          <el-radio-group v-model="exportOptions.type">
            <el-radio label="current">当前页数据</el-radio>
            <el-radio label="filtered">筛选结果</el-radio>
            <el-radio label="all">全部数据</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="导出格式">
          <el-radio-group v-model="exportOptions.format">
            <el-radio label="xlsx">Excel格式</el-radio>
            <el-radio label="csv">CSV格式</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="包含字段">
          <el-checkbox-group v-model="exportOptions.fields">
            <el-checkbox label="studentName">学生姓名</el-checkbox>
            <el-checkbox label="studentId">学号</el-checkbox>
            <el-checkbox label="examName">考试名称</el-checkbox>
            <el-checkbox label="examTime">考试时间</el-checkbox>
            <el-checkbox label="score">总分</el-checkbox>
            <el-checkbox label="isPassed">是否通过</el-checkbox>
            <el-checkbox label="cheatingFlag">作弊标记</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="exportVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmExport" :loading="exportLoading">
            开始导出
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()

interface GradeItem {
  id: number;
  studentId: number;
  studentName: string;
  examId: number;
  examName: string;
  examStartTime: string;
  examEndTime: string;
  startTime: string;
  submitTime: string;
  score: number;
  status: number;
  isPassed: boolean;
  attemptNumber: number;
  cheatingFlag: number;
  cheatingEvidence: string;
  createdAt: string;
  updatedAt: string;
}

// 搜索表单
const searchForm = reactive({
  studentName: '',
  examTitle: '',
  dateRange: [],
  isPassed: '',
  status: ''
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const gradeList = ref([])

// 获取作弊标记类型
const getCheatingTagType = (flag: number) => {
  const map: Record<number, string> = {
    0: 'info',
    1: 'warning',
    2: 'danger'
  }
  return map[flag] || 'info'
}

// 获取作弊标记文本
const getCheatingTagText = (flag: number) => {
  const map: Record<number, string> = {
    0: '无',
    1: '疑似',
    2: '确认'
  }
  return map[flag] || '未知'
}

// 查询参数转换
function buildQuery() {
  return {
    studentName: searchForm.studentName,
    examName: searchForm.examTitle,
    status: searchForm.status,
    isPassed: searchForm.isPassed !== '' ? searchForm.isPassed : undefined,
    page: currentPage.value,
    size: pageSize.value
  }
}

// 获取成绩列表
const fetchGradeList = async () => {
  try {
    const res = await axios.get('/api/exams/grade/page', { params: buildQuery() })
    const page = res.data.data
    gradeList.value = (page.records || []).map((item: any) => ({
      ...item,
      isPassed: item.isPassed,
      score: item.score,
      examTime: item.startTime,
    }))
    total.value = page.total || 0
  } catch (e) {
    gradeList.value = []
    total.value = 0
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchGradeList()
}

// 重置
const handleReset = () => {
  searchForm.studentName = ''
  searchForm.examTitle = ''
  searchForm.dateRange = []
  searchForm.isPassed = ''
  currentPage.value = 1
  fetchGradeList()
}

// 查看详情
const handleDetail = (row: any) => {
  router.push(`/main/grade/detail?examId=${row.examId}&studentId=${row.studentId}`)
}

// 导出相关状态
const exportLoading = ref(false)
const exportVisible = ref(false)
const exportOptions = reactive({
  type: 'filtered', // current, filtered, all
  format: 'xlsx', // xlsx, csv
  fields: ['studentName', 'studentId', 'examName', 'examTime', 'score', 'isPassed', 'cheatingFlag']
})

// 显示导出对话框
const showExportDialog = () => {
  exportVisible.value = true
}

// 导出成绩
const handleExport = () => {
  showExportDialog()
}

// 确认导出
const confirmExport = async () => {
  try {
    exportLoading.value = true
    const exportParams = {
      ...exportOptions,
      query: exportOptions.type === 'all' ? {} : buildQuery()
    }
    
    const response = await axios.post('/api/exams/grade/export', exportParams, {
      responseType: 'blob'
    })

    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `成绩数据_${new Date().toISOString().slice(0, 10)}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    exportVisible.value = false
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchGradeList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchGradeList()
}

// 首次加载
fetchGradeList()
</script>

<style scoped>
.grade-manage {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  overflow: hidden;
}

.action-card {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.search-form {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  flex-shrink: 0;
}

:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 10px;
}

:deep(.el-table) {
  flex: 1;
  overflow: auto;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

:deep(.el-table .cell) {
  padding-left: 8px;
  padding-right: 8px;
}

.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

:deep(.el-select),
:deep(.el-form-item__content) {
  min-width: 200px;
}
:deep(.el-select-dropdown) {
  min-width: 220px !important;
}
:deep(.el-select-dropdown__item) {
  white-space: normal;
  word-break: break-all;
  min-width: 200px;
}
</style>
